<template>
  <div>
    <el-form
      style="width: 700px"
      :model="form"
      ref="form1"
      class="demo-ruleForm"
      label-width="120px"
      :rules="rules"
    >
      <el-form-item label="分店名称" prop="branchName">
        <el-input v-model="form.branchName"></el-input>
      </el-form-item>
      <el-form-item>
        <div id="container" style="width: 100%; height: 300px"></div>
      </el-form-item>
      <el-form-item label="经度" prop="lng">
        <el-input v-model="form.lng"></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="lat">
        <el-input v-model="form.lat"></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address"></el-input>
      </el-form-item>
      <el-form-item label="省份" prop="province">
        <el-input v-model="form.province"></el-input>
      </el-form-item>
      <el-form-item label="城市" prop="city">
        <el-input v-model="form.city"></el-input>
      </el-form-item>
      <el-form-item label="区县" prop="district">
        <el-input v-model="form.district"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" @click="add(form1)" round>新增</el-button>
        <el-button type="warning" v-on:click="resetForm(form1)" round
          >取消</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import $http from "@/http";
import { onMounted, ref, reactive, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { el } from "element-plus/es/locale";
import { clippingParents } from "@popperjs/core";
const form1 = ref<FormInstance>();
const router = useRouter();
let map = reactive<any>({});
let marker = reactive<any>({});
let form = reactive({
  branchName: "",
  address: "",
  province: "",
  city: "",
  district: "",
  lng: "",
  lat: "",
});

let rules = reactive({
  branchName: [
    { required: true, message: "分店名称不能为空", trigger: "blur" },
  ],
  address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
  province: [{ required: true, message: "省份不能为空", trigger: "blur" }],
  city: [{ required: true, message: "城市不能为空", trigger: "blur" }],
  district: [{ required: true, message: "区县不能为空", trigger: "blur" }],
  lng: [{ required: true, message: "经度不能为空", trigger: "blur" }],
  lat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
});

//提交表单
const add = (fo: FormInstance | undefined) => {
  if (!fo) return;
  fo.validate((valid, field) => {
    if (valid) {
      $http.branchApi
        .add(form)
        .then((res) => {
          // console.log(res)
          if (res.data.code == 200) {
            ElMessage.success("分店添加成功");
            router.push("/home/branch-list");
          }
        })
        .catch((err) => console.log(err));
    } else {
      ElMessage.error("表单填写错误");
    }
  });
};

// 重置表单
const resetForm = (fo: FormInstance | undefined) => {
  if (!fo) return;
  fo.resetFields();
};

const getAddress = (AMap: any, [lng, lat]: any) => {
  const geocoder = new AMap.Geocoder();
  geocoder.getAddress([lng, lat], (status: any, result: any) => {
    const res = result.regeocode;
    form.address = res.formattedAddress;
    form.province = res.addressComponent.province;
    form.city = res.addressComponent.city;
    form.district = res.addressComponent.district;
    form.lng = lng;
    form.lat = lat;
  });
};

onMounted(() => {
  // 加载地图

  (window as any)._AMapSecurityConfig = {
    securityJsCode: "bee20c2976b1de18f0d3ac5c9d5b67d4",
  };
  AMapLoader.load({
    key: "75e8ca8ee8d5e36f3949b602eb79c999", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  })
    .then((AMap) => {
      map = new AMap.Map("container");
      map.on("click", (ev: any) => {
        const { lng, lat } = ev.lnglat;
        let len = Object.keys(marker);
        //!(len.length>0)
        if (len.length > 0) {
          marker.setPosition([lng, lat]);
        } else {
          marker = new AMap.Marker({
            position: [lng, lat],
          });
          map.add(marker);
        }

        getAddress(AMap, [lng, lat]);
      });
    })
    .catch((e) => {
      console.log(e);
    });
});
</script>

<style lang="scss" scoped>
</style>